package Utils;

import core.JitAdd;
import core.JitCommit;
import fileoperation.FileReader;
import gitobject.Blob;
import gitobject.Commit;
import gitobject.GitObject;
import gitobject.Tree;
import repository.Repository;
import sha1.SHA1;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

public class commitUtils {

    public static boolean checkAndUpdateIndex() throws Exception {
        //1.挨个检查index中的文件是否存在，如果存在的话，是否有变化，如果没有变化就跳过
        List<String> allLines = Files.readAllLines(Paths.get(tempWorkTree.indexLoc));
        StringBuilder stringBuilder = new StringBuilder();
        for (String allLine : allLines) {//遍历index文件，每次取出一行
            String key= FileReader.readObjectFileName(allLine);
            String path=FileReader.readObjectKey(allLine);
            File file = new File(path);
            if(!file.exists()) {//说明文件不存在了,需要删除index记录
                allLine="";
            }else if(!key.equals(SHA1.getHash(file))){//说明文件发生变动，需要重新写入
                Blob blob = new Blob(file);
                if(Blob.deserialize(blob.getKey())==null)//如果改变后的文件没有object对象的话,就写入
                    blob.writeObject();
                allLine=blob.getFmt() + " " + blob.getKey() + " " + path+"\n";
            }
                stringBuilder.append(allLine+"\n");
        }
        FileOutputStream fileOutputStream = new FileOutputStream(tempWorkTree.indexLoc);
        fileOutputStream.write(stringBuilder.toString().getBytes(StandardCharsets.UTF_8));
        fileOutputStream.close();
        return true;
    }

    public static Tree rootFloor() throws Exception {
        //得到根目录的tree，其实在serFiles可以得到，但是写乱了，以后再看看吧(爬 以后也不看)
        String index=addUtils.readAllIndex(tempWorkTree.indexLoc);
        File dir = new File(tempWorkTree.workTree);
        StringBuilder stringBuilder = new StringBuilder();
        Blob tempBlob = null;
        Tree tempTree = null;
        Tree tree = new Tree(new File(tempWorkTree.workTree));
        File[] fs = dir.listFiles();
        List list = Tree.sortFile(fs);
        String s = Commit.getLastCommit();
        for (Object o : list) {
            File file = (File) o;
            if (file.isFile()) {//当前遍历的是文件
                    if (index.contains(file.getPath())&&(JitCommit.lastIndex.contains(file.getPath())||file.getPath().contains(JitCommit.tempCommitpath))) {
                        tempBlob = Blob.deserialize(SHA1.getHash(file));
                        stringBuilder.append(tempBlob.getFmt() + " " + file.getName() + " " + tempBlob.getKey() + "\n");
                }
            } else if (file.isDirectory() && !file.getName().equals(".jit")) {
                if (index.contains(file.getPath())&&(JitCommit.lastIndex.contains(file.getPath())||file.getPath().contains(JitCommit.tempCommitpath))) {
                    String ss = Tree.DirSHA1(file);
                    tempTree = Tree.deserialize(ss);
                    stringBuilder.append(tempTree.getFmt() + " " + file.getName() + " " + tempTree.getKey() + "\n");
                }
            }
        }
        tree.setValue(stringBuilder.toString());
        return tree;
    }

    //查找在上一次提交的tree中有没有出现过这个file（文件或文件夹）
    public static boolean existInLast(Tree tree, File file) throws IOException {
        ArrayDeque<Tree> que = new ArrayDeque<>();
        que.add(tree);
        while (que != null) {
            Tree tempTree = que.poll();
            String tempValue = tempTree.getValue();
            if (tempValue.contains(file.getPath()))
                return true;
            //将该tree下一层的所有tree文件加入队列
            ArrayList<String> valueList = FileReader.readByBufferReader(tempValue);
            for (String line : valueList) {
                String fmt=FileReader.readObjectFmt(line);
                String key=FileReader.readObjectKey(line);
                if(fmt.equals("tree")){
                    Tree temp=Tree.deserialize(key);
                    que.add(temp);
                }
            }
        }
        return false;
    }


}


